import router from './router'
import store from './store'
import NProgress from 'nprogress' // progress bar
import 'nprogress/nprogress.css' // progress bar style
import {
  getToken
} from '@/utils/auth' // get token from cookie
import getPageTitle from '@/utils/get-page-title'

NProgress.configure({
  showSpinner: false
}) // NProgress Configuration

const whiteList = ['/login', '/logins', '/register', '/forgetpwd'] // no redirect whitelist

router.beforeEach(async (to, from, next) => {
  // start progress bar
  NProgress.start()
  // set page title
  document.title = getPageTitle()

  // determine whether the user has logged in
  const hasToken = getToken()
  if (hasToken) {
    if (to.path === '/login') {
      console.log('1,start')
      // if is logged in, redirect to the home page
      next({
        path: '/'
      })
      // NProgress.done()
      console.log('1,end')
    } else {
      const hasGetUserInfo = store.getters.userInfo
      if (hasGetUserInfo) {
        next()
      } else {
        if (store.getters.roles.length === 0) { // 判断当前用户是否已拉取完user_info信息
          // console.log('3,start')
          store.dispatch('user/getInfo').then(res => { // 拉取info
            // console.log('5,start')
            const power = []
            power.push(res.power.toString())
            const roles = power
            // const roles = ['admin']
            store.dispatch('permission/generateRoutes', {
              roles
            }).then(() => { // 生成可访问的路由表
              router.addRoutes(store.getters.addRoutes) // 动态添加可访问路由表
              next({
                ...to,
                replace: true
              }) // hack方法 确保addRoutes已完成 ,set the replace: true so the navigation will not leave a history record
            })
            // console.log('5,end')
          }).catch(err => {
            console.log(err)
          })
          // console.log('3,end')
        } else {
          next() // 当有用户权限的时候，说明所有可访问路由已生成 如访问没权限的全面会自动进入404页面
        }
      }
    }
  } else {
    if (whiteList.indexOf(to.path) !== -1) {
      next()
    } else {
      next(`/login?redirect=${to.path}`)
      NProgress.done()
    }
  }
})

router.afterEach(() => {
  // finish progress bar
  NProgress.done()
})
